/*
** serveur_ftp.c for ftp in /home/morgan_t/Documents/svn-for-my-proj/tek2/UNIX/my_ftp
** 
** Made by thomas morgant
** Login   <morgan_t@epitech.net>
** 
** Started on  Tue Apr  3 15:46:05 2012 thomas morgant
** Last update Sun Apr  8 16:00:26 2012 thomas morgant
*/

#include "ftp.h"

void	client_connect(int port, SOCK sock)
{
  t_socket_in	csin;
  SOCK		csock;
  socklen_t	crecsize;
  pid_t		pid;
  char		*cmd;

  cmd = malloc(sizeof(cmd));
  crecsize = sizeof(csin);
  while (1)
    {
      printf("Socket Listen %d ...\n", port); 
      csock = accept(sock, (t_socket *)&csin, &crecsize);
      printf("A client is connecting with socket %d\n", sock);
      if ((pid = fork()) == 0)
	{
	  closesocket(csock);
	  client_connect(port, sock);
	}
      if (!strncmp(fgets(cmd, sizeof(cmd), stdin), "quit", 4))
	{
	  printf("Close client socket\n");
	  closesocket(csock);
	  exit(EXIT_SUCCESS);
	}
    }
}

int	init_serv(int port)
{
  t_socket_in	sin;
  SOCK		ssock;
  socklen_t	recsize;
 
  recsize = sizeof(sin);
  ssock = socket(AF_INET, SOCK_STREAM, 0);
  if (ssock != INVALID_SOCKET)
    printf("La socket %d est maintenant ouverte en mode TCP\n", ssock);
  sin.sin_addr.s_addr = htonl(INADDR_ANY);
  sin.sin_family = AF_INET;
  sin.sin_port = htons(port);
  if (bind(ssock, (t_socket *)&sin, recsize) == SOCKET_ERROR)
    fprintf(stderr, "Error of Bind!\n");
  else
    if (listen(ssock, 5) == SOCKET_ERROR)
      fprintf(stderr, "Error of Listen\n");
    else
      client_connect(port, ssock);
  return (EXIT_SUCCESS);
}

int	main(int ac, char **av)
{
  int	port;

  if (ac != 2)
    {
      fprintf(stderr, "Usage: %s [port]\n", av[0]);
      exit(EXIT_FAILURE);
    }
  port = atoi(av[1]);
  init_serv(port);
  return (EXIT_SUCCESS);
}
